import { Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { PrismaService } from '@/prisma/prisma.service';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class ArticleService {

  constructor(private readonly prisma :PrismaService,private config :ConfigService){}

  create(createArticleDto: CreateArticleDto) {
    return this.prisma.article.create({
      data:{
        title:createArticleDto.title,
        content:createArticleDto.content,
        categoryId:+createArticleDto.categoryId
      }
    })
  }

  // 查找所有文章
  async findAll(page = 1) {
   const row =  this.config.get('ARTICLE_PAGE_ROW')
   
    const article =  await this.prisma.article.findMany({
      skip:(page-1) * row,
      take: +row
    })
    console.log(article.length);
    
    const total = await this.prisma.article.count()
    return {
      meta:{
        current_page:page,  // 第几页
        page_row:row,  // 显示几条
        total,  // 总条数
        total_page:Math.ceil(total / row)  // 总页数
      },
      data:article
    }
  }

  findOne(id: number) {
    return this.prisma.article.findFirst({
      where:{
        id:+id
      }
    })
  }

  update(id: number, updateArticleDto: UpdateArticleDto) {
    return this.prisma.article.update({
      where:{
        id:+id
      },
      data:{
        ...updateArticleDto,
        title:updateArticleDto.title,
        content:updateArticleDto.content,
        categoryId:updateArticleDto.categoryId

      }
    })
  }

  remove(id: number) {
    return this.prisma.article.delete({
      where:{
        id
      }
    })
  }
}
